package com.problem.leetcode;

/**
 * 解题思路:设置一个变量判断是否需要进位操作，注意如果一直进位 最值用的数组元素个数就会加一，考虑这种情况
 *
 * @author didi
 * @DESCRIPTION
 * @create 2019-04-23 13:18
 **/

public class Problem66 {
    public int[] plusOne(int[] digits) {
        return plusOne(digits, 1);
    }

    public int[] plusOne(int[] digits, int num) {
        int remain = 0;
        int begin  = digits.length - 1;

        while (begin >= 0) {
            int tmp = (begin == digits.length - 1) ? (digits[begin] + num) : digits[begin];
            tmp = remain > 0 ? tmp + 1 : tmp;
            remain = tmp / 10;
            tmp = tmp % 10;
            digits[begin--] = tmp;
        }
        if (remain > 0) {
            int   digit  = getNumLenght(remain);
            int[] result = new int[digits.length + digit];
            System.arraycopy(digits, 0, result, result.length - digits.length, digits.length);

            for (int i = result.length - digits.length - 1; i >= 0; i--) {
                result[i] = remain % 10;
                remain /= 10;
            }

            return result;
        } else {
            return digits;
        }
    }

    private static int getNumLenght(long num) {
        num = num > 0 ? num : -num;
        if (num == 0) {
            return 1;
        }
        return (int) Math.log10(num) + 1;
    }
}
